using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using ScriptEase.Shell.Controls;
using ScriptEase.Shell.Events;



namespace ScriptEase.Shell.Commands
{
    internal class GetLatestMergeCommand : ICommand
    {
        private readonly ShellViewModel _shellViewModel;
        private readonly WebResourceStatusView _viewModel;



        public GetLatestMergeCommand(ShellViewModel shellViewModel, WebResourceStatusView viewModel)
        {
            _shellViewModel = shellViewModel;
            _viewModel = viewModel;
        }



        public void Execute(object parameter)
        {
            MappingModel[] selectedItems = _viewModel.SelectedItems.Where(
                item => item.SyncStatus != FileSyncStatus.Publishing
                        && item.SyncStatus != FileSyncStatus.Updating).ToArray();

            IEnumerable<string> selectedWebResourceNames = from item in selectedItems select item.WebResourceName;
            _shellViewModel.Project.UpdateLocal(selectedWebResourceNames.ToArray(), ConflictResolver.CreateMergeFile);
        }



        public bool CanExecute(object parameter)
        {
            return ( _shellViewModel.ProjectLoadStatus == ProjectStatus.Connected && 
                            _viewModel.SelectedItems.Any(item => item.SyncStatus != FileSyncStatus.Publishing &&
                                                                 item.SyncStatus != FileSyncStatus.Updating));
        }



        public event EventHandler CanExecuteChanged;
    }
}